"""
对话和消息模型
"""

from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Boolean, JSON
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base


class Conversation(Base):
    """对话会话表"""
    
    __tablename__ = "conversations"
    
    id = Column(Integer, primary_key=True, index=True, comment="会话ID")
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False, comment="用户ID")
    title = Column(String(200), comment="会话标题")
    model_config_id = Column(Integer, ForeignKey("model_configs.id"), comment="使用的模型配置ID")
    knowledge_base_id = Column(Integer, ForeignKey("knowledge_bases.id"), comment="使用的知识库ID")
    prompt_template_id = Column(Integer, ForeignKey("prompt_templates.id"), comment="使用的提示词模板ID")
    is_active = Column(Boolean, default=True, comment="是否活跃")
    message_count = Column(Integer, default=0, comment="消息数量")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关系
    user = relationship("User", back_populates="conversations")
    model_config = relationship("ModelConfig")
    knowledge_base = relationship("KnowledgeBase", lazy="select")
    prompt_template = relationship("PromptTemplate", lazy="select")
    messages = relationship("Message", back_populates="conversation", cascade="all, delete-orphan")
    
    def __repr__(self):
        return f"<Conversation(id={self.id}, user_id={self.user_id}, title='{self.title}')>"


class Message(Base):
    """消息表"""
    
    __tablename__ = "messages"
    
    id = Column(Integer, primary_key=True, index=True, comment="消息ID")
    conversation_id = Column(Integer, ForeignKey("conversations.id"), nullable=False, comment="会话ID")
    role = Column(String(20), nullable=False, comment="角色：user/assistant/system")
    content = Column(Text, nullable=False, comment="消息内容")
    message_metadata = Column(JSON, comment="消息元数据")
    token_count = Column(Integer, comment="token数量")
    created_at = Column(DateTime(timezone=True), server_default=func.now(), comment="创建时间")
    
    # 关系
    conversation = relationship("Conversation", back_populates="messages")
    
    def __repr__(self):
        return f"<Message(id={self.id}, conversation_id={self.conversation_id}, role='{self.role}')>"
